package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryService categoryService;

    @PostMapping()
    public R<Long> category(@RequestBody Category category){
        categoryMapper.insert(category);
        return R.success(category.getId());
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){
        Page<Category> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.select();
        wrapper.orderByAsc(Category::getSort);
        categoryMapper.selectPage(pageInfo, wrapper);
        return R.success(pageInfo);

    }

    @DeleteMapping
    public R<String> delete(Long id){
        categoryService.delete(id);
        return R.success("删除成功！");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功！");
    }

//    @GetMapping("/list")
//    public R<List<Category>> list(Category category){
//        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Category::getType, category.getType())
//                .orderByDesc(Category::getUpdateTime);
//        List<Category> list = categoryService.list();
//        return R.success(list);
//    }
    @GetMapping("/list")
    public R<List<Category>> list(){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list();
        return R.success(list);
    }
}
